<template>
  <view class="module-manage-container">
    <nav-header title="模块管理"></nav-header>
    
    <view class="content" :style="{ paddingTop: statusBarHeight + 44 + 'px' }">
      <!-- Active Modules -->
      <view class="section">
        <view class="section-title">使用中的模块：</view>
        <drag-sort-vue3
          :list="activeModulesList"
          :props="{ label: 'modelName' }"
          @change="onActiveSortChange"
          @update:active="onUpdateActive"
          @update:list="list => onUpdateActiveList(list, 'active')"
        ></drag-sort-vue3>
      </view>
      
      <!-- Inactive Modules -->
      <view class="section">
        <view class="section-title">未使用的模块：</view>
        <drag-sort-vue3
          :list="inactiveModulesList"
          :props="{ label: 'modelName' }"
          @change="onInactiveSortChange"
          @update:active="onUpdateActive"
          @update:list="list => onUpdateActiveList(list, 'inactive')"
        ></drag-sort-vue3>
      </view>
      
      <!-- Save Button -->
      <view class="save-action">
        <button class="save-btn" @click="saveSettings">保存设置</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useResumeStore } from '@/store/resume.js'
import NavHeader from '@/components/nav-header.vue'
import dragSortVue3 from '@/uni_modules/drag-sort-vue3/components/drag-sort-vue3/drag-sort-vue3.vue'
import { getModelList, updateResumeModel } from '@/api/module.js'

const resumeStore = useResumeStore()
const statusBarHeight = ref(20)
const activeModulesList = ref([])
const inactiveModulesList = ref([])
const originalModules = ref([])
    
onMounted(() => {
      const systemInfo = uni.getSystemInfoSync()
      statusBarHeight.value = systemInfo.statusBarHeight
      resumeStore.loadFromStorage()
  getModelList({resumeId:resumeStore.resumeId}).then(res => {
    if(res.code == 200){
      activeModulesList.value = res.rows.map((item, idx) => ({
        ...item,
        active: true,
        removable: item.modelName == '个人信息' ? false : true,
        sortNum: idx + 1
      }))
      // 生成未激活模块
      inactiveModulesList.value = resumeStore.modules
        .filter(m => !activeModulesList.value.some(a => a.modelName === m.modelName))
        .map((m, idx) => ({
          ...m,
          active: false,
          sortNum: activeModulesList.value.length + idx + 1
        }))
    }
    console.log('activeModulesList.value',activeModulesList.value);
    console.log('inactiveModulesList.value',inactiveModulesList.value);
    // 用深拷贝保存originalModules
    resumeStore.modules = [...activeModulesList.value, ...inactiveModulesList.value]
    originalModules.value = JSON.parse(JSON.stringify([...activeModulesList.value, ...inactiveModulesList.value]))
    console.log('originalModules.value：',originalModules.value);
  })
})

const onActiveSortChange = (changeObj) => {
  console.log('onActiveSortChange',changeObj);
  // changeObj 不是数组，不能 forEach
  // 排序后，activeModulesList 已自动同步，直接保存即可
  resumeStore.saveToStorage()
}

const onInactiveSortChange = (changeObj) => {
  // changeObj 不是数组，不能 forEach
  // 排序后，inactiveModulesList 已自动同步，直接保存即可
  resumeStore.saveToStorage()
}

const onUpdateActive = ({ modelName, active }) => {
  console.log('onUpdateActive',modelName,active);
  // 在activeModulesList和inactiveModulesList中查找该项
  let fromList = active ? inactiveModulesList : activeModulesList
  let toList = active ? activeModulesList : inactiveModulesList
  const idx = fromList.value.findIndex(item => item.modelName === modelName)
  if (idx !== -1) {
    const [item] = fromList.value.splice(idx, 1)
    item.active = active
    toList.value.push(item)
  }
  resumeStore.saveToStorage()
}

const onUpdateActiveList = (list, type) => {
  // 拖拽后重排sort
  if (type === 'active') {
    list.forEach((item, idx) => item.sortNum = idx + 1)
    activeModulesList.value = list
  } else {
    list.forEach((item, idx) => item.sortNum = activeModulesList.value.length + idx + 1)
    inactiveModulesList.value = list
  }
  console.log('activeModulesList.value',activeModulesList.value);
  console.log('inactiveModulesList.value',inactiveModulesList.value);
  resumeStore.modules = [...activeModulesList.value, ...inactiveModulesList.value]
  resumeStore.saveToStorage()
}
    
const saveSettings = async () => {
      try {
    // 1. 获取保存前后的模块状态
    const beforeActiveIds = originalModules.value.filter(m => m.active).map(m => m.modelName)
    const beforeInactiveIds = originalModules.value.filter(m => !m.active).map(m => m.modelName)
    const afterActiveIds = activeModulesList.value.map(m => m.modelName)
    const afterInactiveIds = inactiveModulesList.value.map(m => m.modelName)

    // 2. 找出需要删除的模块（原本active，现在inactive）
    const toDelete = beforeActiveIds.filter(modelName => afterInactiveIds.includes(modelName))
    // 3. 找出需要新增的模块（原本inactive，现在active）
    const toAdd = beforeInactiveIds.filter(modelName => afterActiveIds.includes(modelName))
    console.log('toDelete',toDelete);
    console.log('toAdd',toAdd);
    // 4. 执行删除
    for (const modelName of toDelete) {
      const module = resumeStore.modules.find(m => m.modelName === modelName)
      // 只删除有modelId的模块
      if (module && module.modelId) {
        await resumeStore.detResumeModelFun(module.modelId)
        // 删除后清空modelId
        module.modelId = ''
        module.resumeId = ''
      }
    }
    // 5. 执行新增
    for (const modelName of toAdd) {
      const module = resumeStore.modules.find(m => m.modelName === modelName)
      // 只新增没有modelId的模块
      if (module) {
        console.log('新增模块',module);
        const res = await resumeStore.addResumeModelFun({
          resumeId: resumeStore.resumeId,
          modelName: module.modelName
        })
        // 新增后赋值modelId
        if (res && res.data) {
          module.modelId = res.data
          module.resumeId = resumeStore.resumeId
        }
      }
    }

    originalModules.value = JSON.parse(JSON.stringify([...activeModulesList.value, ...inactiveModulesList.value]))
    // 6、修改模块接口，及模块位置
    await updateResumeModel(activeModulesList.value).then(res => {
      if(res.code == 200){
        uni.showToast({ title: '保存成功', icon: 'success' })
        setTimeout(() => { uni.navigateBack() }, 1500)
      }
    })

    // 6. 保存到本地前，重设sort
    // activeModulesList.value.forEach((m, idx) => m.sort = idx + 1)
    // inactiveModulesList.value.forEach((m, idx) => m.sort = activeModulesList.value.length + idx + 1)
    // resumeStore.modules = [...activeModulesList.value, ...inactiveModulesList.value]
    // console.log('重设sort后：',resumeStore.modules);
    // resumeStore.saveToStorage()
    // 7. 更新 originalModules（用深拷贝）
    // uni.showToast({ title: '保存成功', icon: 'success' })
    // setTimeout(() => { uni.navigateBack() }, 1500)
  } catch (error) {
    uni.showToast({ title: error.message || '保存失败，请重试', icon: 'none' })
  }
}
</script>

<style lang="scss" scoped>
.module-manage-container {
  min-height: 100vh;
  background-color: #F8F8F8;
  
  .content {
    padding: 16px;
    
    .section {
      margin-bottom: 20px;
      
      .section-title {
        font-size: 15px;
        color: #666;
        margin-bottom: 12px;
      }
      
      .module-list {
        min-height: 60px;
      }
    }
    
    .save-action {
      margin-top: 30px;
      
      .save-btn {
        width: 100%;
        height: 44px;
        line-height: 44px;
        background-color: #5ac725;
        color: #FFFFFF;
        font-size: 16px;
        font-weight: 500;
        border-radius: 22px;
        box-shadow: 0 2px 8px rgba(90, 199, 37, 0.3);
      }
    }
  }
}

// Sortable相关样式
.sortable-ghost {
  opacity: 0.5;
  background-color: #c8e6c9;
}

.sortable-chosen {
  background-color: #f0f9ff;
}

.sortable-drag {
  z-index: 1000;
}

.sortable-fallback {
  box-shadow: 0 5px 15px rgba(0,0,0,0.2);
  transform: rotate(2deg);
  z-index: 1000;
}

.module-wrap {
  transition: transform 0.2s ease;
  
  &:active {
    transform: scale(1.02);
  }
}

/* 拖动时禁止页面滚动 */
:global(.sortable-dragging) {
  overflow: hidden !important;
  touch-action: none !important;
}
</style> 